package me.jiatao.ipc;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;

import me.jiatao.ipc.service.LocalService;
import me.jiatao.ipc.service.MessengerService;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    private LocalService localService;
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            LocalService.LocalBinder localBinder = (LocalService.LocalBinder) service;
            localService = localBinder.getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.e("******", "onServiceDisconnected");
        }
    };

    public void bindService(View view) {
        Log.e("******", "onServiceDisconnected");
        Intent intent = new Intent(this, LocalService.class);
        bindService(intent, serviceConnection, BIND_AUTO_CREATE);
    }

    public void getNumber(View view) {
        if (localService != null) {
            int num = localService.getRandomNumber();
            Log.e("******", "获取的随机数是：" + num);
        }
    }

    /*****************************************************/
    private Messenger messenger;
    private ServiceConnection msgServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.e("******", "msgServiceConnection：");
            messenger = new Messenger(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.e("******", "msgServiceConnection onServiceDisconnected");
        }
    };

    public void bindMsgService(View view) {
        Intent intent = new Intent();
        intent.setAction("me.jiatao.ipc.messenger");
        intent.setPackage("me.jiatao.ipc");
        bindService(intent, msgServiceConnection, BIND_AUTO_CREATE);
    }

    public void msgHello(View view) {
        Message msg = Message.obtain(null, MessengerService.MSG_SAY_HELLO, 0, 0);
        try {
            messenger.send(msg);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
}
